//
//  Date.swift
//  BaseModule_Example
//
//  Created by seven on 2020/7/1.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit

public extension Date {
    /// 是否今天
    func isToday() -> Bool {
        let calendar = Calendar.current
        let set: Set<Calendar.Component> = [.year, .month, .day]

        let selfCmp = calendar.dateComponents(set, from: self)
        let nowCmp = calendar.dateComponents(set, from: Date())

        return selfCmp.year == nowCmp.year
            && selfCmp.month == nowCmp.month
            && selfCmp.day == nowCmp.day
    }

    /// 是否昨天
    func isYesterday() -> Bool {
        let fmt = DateFormatter()
        fmt.dateFormat = "yyyy-MM-dd"
        let selfDate = fmt.date(from: fmt.string(from: self))!
        let nowDate = fmt.date(from: fmt.string(from: Date()))!
        let calendar = Calendar.current
        let set: Set<Calendar.Component> = [.day]
        let cmp = calendar.dateComponents(set, from: selfDate, to: nowDate)
        return cmp.day == 1
    }

    /// 返回格式化好的string
    func formattedString() -> String {
        let fmt = DateFormatter()
        let date = self
        let timeStamp = abs(date.timeIntervalSinceNow)

        var str = ""
        if date.isYesterday() {
            fmt.dateFormat = "HH:mm"
            str = "昨天 \(fmt.string(from: date))"
        } else if date.isToday() {
            if timeStamp < 60 { // 1分钟内
                str = "刚刚"
            } else if timeStamp < 60 * 60 { // 1小时内
                str = "\(Int(timeStamp) / 60)分钟前"
            } else if timeStamp < 60 * 60 * 24 { // 1天内
                fmt.dateFormat = "HH:mm"
                str = "今天 \(fmt.string(from: date))"
            } else {
                fmt.dateFormat = "MM-dd"
                str = fmt.string(from: date)
            }
        } else {
            fmt.dateFormat = "yyyy-MM-dd"
            str = fmt.string(from: date)
        }
        return str
    }
}
